package com.quick.framework.aspectj;

import com.quick.common.annotation.DataScopeByGetInfo;
import com.quick.common.core.event.DataScopeEvent;
import com.quick.common.exception.ServiceException;
import com.quick.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;


/**
 * @author 喵煞
 */
@Aspect
@Component
@Slf4j
public class DataScopeByGetInfoAspect {
    @Autowired
    private ApplicationContext applicationContext;

    @Before("@annotation(dataScopeByGetInfo)")
    public void doBefore(JoinPoint point, DataScopeByGetInfo dataScopeByGetInfo) {
        Object params = point.getArgs()[0];
        String fieldKey = dataScopeByGetInfo.field();
        try {
            if (StringUtils.isNotEmpty(fieldKey) && params != null) {
                Class<?> aClass = params.getClass();
                Object fieldValue;
                if (params instanceof Number || aClass.isArray()) {
                    fieldValue = params;
                } else {
                    Field field = aClass.getDeclaredField(fieldKey);
                    field.setAccessible(true);
                    fieldValue = field.get(params);
                    field.setAccessible(false);
                }
                applicationContext.publishEvent(new DataScopeEvent(this, fieldValue, dataScopeByGetInfo.type()));
            }
        } catch (Exception e) {
            throw new ServiceException("没有访问用户数据的权限", e);
        }
    }
}

